package com.zentrale1.noodlemail;
import javax.mail.*;
import javax.mail.internet.*;
import java.io.*;
import java.text.ParseException;
import java.util.Date;
import java.util.Enumeration;
import java.util.Properties;

/*
 * The MIT License
 * 
 * Copyright (c) 2010 Andreas Fleig
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 */


/**
 * Generates Mail objects from files
 * @author afleig
 *
 */
public class MailFactory 
{
	/**
	 * Generates a Mail object from an email stored in a file
	 * @param path full path to an email file
	 * @return Mail object
	 */
	public static Mail parse(String path)
	{
		Mail mail = new Mail();
		try {
			Session s = Session.getDefaultInstance(new Properties());
			FileInputStream fileInput = new FileInputStream(path);
			MimeMessage message = new MimeMessage(s, fileInput);
			
			setHeaders(mail, message);
			setBody(mail, message);
			
			MailIndex index = MailIndex.getInstance();
			index.put(mail.getMessageId(), mail);
			
			fileInput.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (MessagingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return mail;
	}
	
	@SuppressWarnings("unchecked")
	private static void setHeaders(Mail mail, MimeMessage message) 
	throws MessagingException
	{
		for (Enumeration<Header> e = message.getAllHeaders(); 
				e.hasMoreElements(); ) {
			Header line = e.nextElement();
			
			if (line.getName().equals("Subject"))
				mail.setSubject(line.getValue());
			
			if (line.getName().equals("Message-ID"))
				mail.setMessageId(line.getValue());
			
			if (line.getName().equals("In-Reply-To"))
				mail.setReplyTo(line.getValue());
			
			if (line.getName().equals("From"))
				mail.setFrom(line.getValue());
			if (line.getName().equals("Date"))
				setDate(mail, line.getValue());
		}
	}
	
	private static void setDate(Mail mail, String dateString)
	{
		MailDateFormat m = new MailDateFormat();
		Date d;
		try {
			d = m.parse(dateString);
		} catch (ParseException e) {
			e.printStackTrace();
			d = new Date();
		}
		mail.setDate(d);
	}
	
	private static void setBody(Mail mail, MimeMessage message)
	throws MessagingException, IOException
	{
		String[] ct = message.getContentType().split(";");

		addToBody(mail, ct[0], message);
	}
	
	private static void parseMulti(Mail mail, String contentType, Part part) 
	throws IOException, MessagingException
	{
		if (contentType.equals("multipart/mixed") 
				|| contentType.equals("multipart/alternative")
				|| contentType.equals("multipart/related")
				|| contentType.equals("multipart/signed")) {
			MimeMultipart multi = (MimeMultipart)part.getContent();
			for (int i=0; i<multi.getCount(); i++) {
				BodyPart subPart = multi.getBodyPart(i);
				
				String[] ct = subPart.getContentType().split(";");
				addToBody(mail, ct[0], subPart);
			}
		}		
	}
	

	private static void addToBody(Mail mail, String contentType, Part part) 
	throws IOException, MessagingException
	{
		// TODO add content instead of replacing,
		//      or check which part is more important
		if (contentType.equals("text/plain")) { 
			mail.setTextBody((String)part.getContent());
		}
		
		if (contentType.equals("text/html")) { // TODO strip html tags
			mail.setTextBody((String)part.getContent());
		}
		
		if (contentType.equals("multipart/mixed") 
				|| contentType.equals("multipart/alternative")
				|| contentType.equals("multipart/signed")) {
			parseMulti(mail, contentType, part);
		}
		
	}
	
}
